package com.ygxsk.carhome.ui.archive;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.alertview.OnItemClickListener;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.ArchiveUpdateType;
import com.ygxsk.carhome.enumwrap.LeadGender;
import com.ygxsk.carhome.event.EventArchiveDetail;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.response.LeadsGenderInfoBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.rxbus.RxBusGender;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.leads.LeadsGenderSelectPopu;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.utils.ViewUitls;
import com.ygxsk.carhome.views.ClearEditTextTouch;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-29  16:09
 * @Description:客户信息的编辑页面
 */
public class CustomerInfoEditActivity extends ErrorActivity implements ErrorParentExtraSingle {

    //客户姓名
    @BindView(R.id.editview_file_name_edit)
    ClearEditTextTouch editview_file_name_edit;

    //选择客户性别
    @BindView(R.id.layoutfilepersonsex_edit)
    LinearLayout layoutfilepersonsex_edit;

    //客户性别
    @BindView(R.id.textview_customer_sex_edit)
    TextView textview_customer_sex_edit;

    //客户年龄
    @BindView(R.id.editview_customer_years_edit)
    ClearEditTextTouch editview_customer_years_edit;

    //客户手机号
    @BindView(R.id.editview_customer_phone_edit)
    ClearEditTextTouch editview_customer_phone_edit;

    //客户微信号
    @BindView(R.id.editview_customer_wechart_edit)
    ClearEditTextTouch editview_customer_wechart_edit;

    //客户邮箱
    @BindView(R.id.editview_customer_email_edit)
    ClearEditTextTouch editview_customer_email_edit;

    //客户地址
    @BindView(R.id.editview_customer_address_edit)
    ClearEditTextTouch editview_customer_address_edit;

    //客户公司
    @BindView(R.id.editview_customer_company_edit)
    ClearEditTextTouch editview_customer_company_edit;

    //客户公司
    @BindView(R.id.editview_customer_job_edit)
    ClearEditTextTouch editview_customer_job_edit;

    //携带的 从列表过来的这条数据
    private InformationManageVoExtra extra_InformationManageVo_extra;

    //获取年龄的信息列表
    private ArrayList<LeadsGenderInfoBean> mDataResources_genderType = new ArrayList<>();

    //客户信息-------------------------------------------------------------------------------
    //上传需要的提供信息 10 个基础信息
    //上传需要的姓名
    private String clientName_upLoad = "";
    //需要上传的身份信息
    private String idCard_upLoad = "";
    //上传需要的性别
    private String gender_upLoad = "";
    //年龄信息
    private String age_upLoad = "";
    //需要上传的手机号信息
    private String phone_upLoad = "";
    //客户的微信号信息
    private String wechatNumber_upLoad = "";
    //客户的邮件信息
    private String email_upLoad = "";
    //客户的地址信息
    private String address_upLoad = "";
    //客户的公司信息
    private String companyDetail_upLoad = "";
    //客户的职位信息
    private String position_upLoad = "";

    //单独的做上传的信息；
    private ClientManageSingleUpLoad clientManage_upLoad = new ClientManageSingleUpLoad();

    //添加 这条档案的id信息；
    private String vehicleId_or_informationId_upLoad = "";

    //获取性别的弹窗内容
    private BasePopupView basePopupViewGender;


    @OnClick({R.id.layoutbuttoncustomerediaddsubmit,//保存提交按钮
            R.id.layoutfilepersonsex_edit//变动客户的年龄信息
    })//
    public void onViewClickInCustomerEdit(View view) {

        switch (view.getId()) {

            case R.id.layoutbuttoncustomerediaddsubmit: {

                //点击保存-做数据校验，有必填项
                //数据填充的各种校验
                //客户信息
                clientName_upLoad = editview_file_name_edit.getText().toString().trim();
                //客户的证件号 是可以为空的 idCard
                idCard_upLoad = "";
                //客户的性别--是上传性别的id信息；
                //gender_upLoad = textview_customer_sex.getText().toString().trim();
                //客户的年龄
                age_upLoad = editview_customer_years_edit.getText().toString().trim();
                //客户的手机号
                phone_upLoad = editview_customer_phone_edit.getText().toString().trim();
                //客户的微信号
                wechatNumber_upLoad = editview_customer_wechart_edit.getText().toString().trim();
                //客户的邮箱信息
                email_upLoad = editview_customer_email_edit.getText().toString().trim();
                //客户的地址信息-不是公司信息
                address_upLoad = editview_customer_address_edit.getText().toString().trim();
                //客户的公司信息
                companyDetail_upLoad = editview_customer_company_edit.getText().toString().trim();
                //客户的职位信息
                position_upLoad = editview_customer_job_edit.getText().toString().trim();

                //可以直接填充客户信息
                if (clientManage_upLoad == null) {
                    clientManage_upLoad = new ClientManageSingleUpLoad();
                }

                clientManage_upLoad.setClientName(clientName_upLoad);
                clientManage_upLoad.setIdCard(idCard_upLoad);
                clientManage_upLoad.setGender(gender_upLoad);
                clientManage_upLoad.setAge(age_upLoad);
                clientManage_upLoad.setPhone(phone_upLoad);
                clientManage_upLoad.setWechatNumber(wechatNumber_upLoad);
                clientManage_upLoad.setEmail(email_upLoad);
                clientManage_upLoad.setAddress(address_upLoad);
                clientManage_upLoad.setCompanyDetail(companyDetail_upLoad);
                clientManage_upLoad.setPosition(position_upLoad);

                //校验客户姓名
                if (TextUtils.isEmpty(clientName_upLoad)) {//服务站运营经理的初始值-1说明没有赋值，提交不过去
                    CommUtils.checkDialog(mAlertView);
                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.check_customername_upload), true);
                    mAlertView.show();
                    return;
                }

                //校验客户的手机号
                if (TextUtils.isEmpty(phone_upLoad)) {//服务站运营经理的初始值-1说明没有赋值，提交不过去
                    CommUtils.checkDialog(mAlertView);
                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.check_customerphone_upload), true);
                    mAlertView.show();
                    return;
                }


                CommUtils.checkDialog(mAlertView);
                mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                        StringUtils.getString(R.string.middlelowmodifychange),//提示内容
                        StringUtils.getString(R.string.clearcachecancel), //取消
                        new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                        null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
                    @Override
                    public void onItemClick(Object o, int position) {

                        if (position != AlertView.CANCELPOSITION) {

                            method_remedialItems_addSubmit_upLoad();

                        }
                    }
                });

                mAlertView.setCancelable(true);
                mAlertView.show();

                break;
            }

            case R.id.layoutfilepersonsex_edit: {//监听客户的性别

                //性别弹窗，做选择
                //"gender": 1, //性别
                KeyboardUtils.hideSoftInput(mActivityInstance);

                LeadsGenderSelectPopu leadsGenderSelectPopu = new LeadsGenderSelectPopu(CustomerInfoEditActivity.this,//
                        ExtraValue.MODIFY_LEAD_GENDER_SELECT_IN_ARCHIVE_FILE_ADD,//
                        mDataResources_genderType);

                //please_choose_person_sex
                leadsGenderSelectPopu.setTitleName(getResources().getString(R.string.please_choose_person_sex));


                //直接弹窗：
                basePopupViewGender = new XPopup.Builder(CustomerInfoEditActivity.this)
                        .hasShadowBg(true)
                        //.moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                        .isViewMode(true)
                        //.autoDismiss(false)
                        //.isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .isThreeDrag(false) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                        //.dismissOnTouchOutside(true)
                        //.notDismissWhenTouchInView()
                        .moveUpToKeyboard(false)
                        .asCustom(leadsGenderSelectPopu)//
                        .show();

                break;
            }

            default:
                break;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //这个也是档案添加的顶部内容

        mActivityInstance = this;

        processExtraData();

        if (mDataResources_genderType == null) {
            mDataResources_genderType = new ArrayList<>();
        }

        initViews();

        //监听性别变动
        mCompositeDisposable.add(RxBus.getInstance()//
                .toObserverable(RxBusGender.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxBusGender>() {//
                    @Override
                    public void accept(RxBusGender rxBusGender) throws Exception {

                        int actionFlag = rxBusGender.getActionFlag();
                        LeadsGenderInfoBean leadsGenderInfoBean = rxBusGender.getLeadsGenderInfoBean();

                        if (actionFlag == ExtraValue.MODIFY_LEAD_GENDER_SELECT_IN_ARCHIVE_FILE_ADD) {//更改了【性别】标志

                            gender_upLoad = leadsGenderInfoBean.getTypeId();

//                            LogUtils.d("itchen---mCompositeDisposable---切换性别-->" + leadsGenderInfoBean);

                            if (textview_customer_sex_edit != null) {
                                textview_customer_sex_edit.setText(leadsGenderInfoBean.getName());
                            }

                        }
                    }
                }));

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fileaddtop_edit;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.add_submit_customer_info));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        toolbarHelper.setLayoutRight(false, 0, "", null);

    }

    @Override
    protected void onClickNodata(View v) {

        //retain


    }

    @Override
    protected void initViews() {

        //直接填充 从详情携带过来的数据

        if (mDataResources_genderType != null) {
            mDataResources_genderType.addAll(ViewUitls.getGenderTypes());
        }

        if (extra_InformationManageVo_extra != null) {

            ClientManageSingleUpLoad _clientManage = extra_InformationManageVo_extra.getClientManageSingleUpLoad();

            if (_clientManage != null) {

                //客户姓名
                CommUtils.setText(editview_file_name_edit, _clientManage.getClientName());

                //同时间设置 向外传递的gender_id_upLoad,因为客户可能并没有修改性别，那么此值做默认；
                gender_upLoad = _clientManage.getGender();

                //客户性别
                String genderType = _clientManage.getGender();
//                LeadGender {
//                    LEAD_GENDER_MEN("0", "男"),
//                    LEAD_GENDER_WOMEN("1", "女"),
//                    LEAD_GENDER_UNKNOW("2", "未知");//未知
                if (TextUtils.equals(genderType, LeadGender.LEAD_GENDER_MEN.getIndex())) {
                    CommUtils.setText(textview_customer_sex_edit, LeadGender.LEAD_GENDER_MEN.getValue());
                } else if (TextUtils.equals(genderType, LeadGender.LEAD_GENDER_WOMEN.getIndex())) {
                    CommUtils.setText(textview_customer_sex_edit, LeadGender.LEAD_GENDER_WOMEN.getValue());
                } else if (TextUtils.equals(genderType, LeadGender.LEAD_GENDER_UNKNOW.getIndex())) {
                    CommUtils.setText(textview_customer_sex_edit, LeadGender.LEAD_GENDER_UNKNOW.getValue());
                }

                //客户年龄
                CommUtils.setText(editview_customer_years_edit, _clientManage.getAge());
                //客户电话
                CommUtils.setText(editview_customer_phone_edit, _clientManage.getPhone());
                //微信号
                CommUtils.setText(editview_customer_wechart_edit, _clientManage.getWechatNumber());
                //邮箱信息
                CommUtils.setText(editview_customer_email_edit, _clientManage.getEmail());
                //地址信息 住址？
                CommUtils.setText(editview_customer_address_edit, _clientManage.getAddress());
                //公司信息
                CommUtils.setText(editview_customer_company_edit, _clientManage.getCompanyDetail());
                //职位信息
                CommUtils.setText(editview_customer_job_edit, _clientManage.getPosition());


            } else {
                //提示处理异常
                ToastUtils.showShort(getString(R.string.action_abnormal));
            }

        }
    }

    @Override
    protected void gainDatas() {

        //

    }

    //这里仅仅是修改客户信息
    private void method_remedialItems_addSubmit_upLoad() {

//                ArchiveUpdateType
//                UPDATETYPE_1("1","整体修改"),
//                UPDATETYPE_2("2","只修改客户信息"),
//                UPDATETYPE_3("3","只修改附件"),
//                UPDATETYPE_4("3","只修改合同"),
//                UPDATETYPE_5("4","只修改车辆信息");

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
//        map.put(Parameterkey.vehicleId, vehicleId_upLoad);
//        map.put(Parameterkey.informationId, vehicleId_upLoad);
        map.put(Parameterkey.informationId, vehicleId_or_informationId_upLoad);

        map.put(Parameterkey.updateType, ArchiveUpdateType.UPDATETYPE_2.getIndex());
        map.put(Parameterkey.clientManage, clientManage_upLoad);

//        updateType
//        1: 整体修改 或者传递空值null
//        2: 只修改客户信息
//        3: 只修改附件
//        4: 只修改合同
//        5: 只修改车辆信息

//        {
//            "clientManage":{
//            "clientName":"张三",
//                    "idCard":"13010818890212122435",
//                    "gender":1,
//                    "age":23,
//                    "phone":"151626332333",
//                    "wechatNumber":"Z_s1234",
//                    "email":"Z_s1234@qq.com",
//                    "address":"河北省石家庄裕华区盛邦花园1区",
//                    "companyDetail":"",
//                    "position":"运维",
//        },
//                "vehicleId":6,
//                "vin":"车架号",
//                "licenseNumber":"冀A88888",
//                "vehicleType":"1",
//                "carBranch":"大众",
//                "carModel":"朗逸运动款",
//                "carSeries":"朗逸",
//                "engineNum":"发动机号",
//                "archivesManageList":[],
//            "informationAccessoryList":[
//            {
//                "filePath":"http://地址",
//                    "fileName":"文件名称",
//                    "fileSize":1023
//            }
//    ]
//        }

//        map.put(Parameterkey.vin, vin_upLoad);//车架号
//        map.put(Parameterkey.licenseNumber, licenseNumber_upLoad);//车牌号
//        map.put(Parameterkey.vehicleType, vehicleType_upLoad);//车辆类型
//        map.put(Parameterkey.carBranch, carBranch_upLoad);//品牌
//        map.put(Parameterkey.carSeries, carSeries_upLoad);//车系
//        map.put(Parameterkey.carModel, carModel_upLoad);//车型
//        map.put(Parameterkey.engineNum, engineNum_upLoad);//发动机号
//
//        map.put(Parameterkey.archivesManageList, _archivesManageList);
//        map.put(Parameterkey.informationAccessoryList, _informationAccessoryList);//是否产生费用

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_ADDINFORMATIONMANAGE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.addInformationManage_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        //上传的json内容是
        String jsonObject_UpLoad = JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL, jsonObject_UpLoad);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateInformationManage(RequestBody.create(jsonObject_UpLoad, MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CustomerInfoEditActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }

                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        //直接刷新档案详情
                        EventArchiveDetail eventArchiveDetail = new EventArchiveDetail();
                        eventArchiveDetail.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_ARCHIVEFILE_DETAIL);
                        EventBus.getDefault().post(eventArchiveDetail);

                        methodSubmitSuccess(CustomerInfoEditActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {
                                //页面关闭直接回到档案管理主页列表页面
                                methodBack();
                            }
                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (basePopupViewGender != null) {
            basePopupViewGender.onDestroy();
            basePopupViewGender = null;
        }

    }

    @Override
    protected void methodBack() {
        ActivityUtils.finishActivity(CustomerInfoEditActivity.this);
    }

    @Override
    public void processExtraData() {

        Bundle extras_bundle = this.getIntent().getExtras();

        if (extras_bundle != null) {

            //flag_jumpfrom_where_type = extras_bundle.getString(ExtraKey.EXTRA_JUMPFROM_WHERE_TYPE);
            extra_InformationManageVo_extra = extras_bundle.getParcelable(ExtraKey.EXTRA_INFORMATION_MANAGE_VO_EXTRA);

            LogUtils.json(ConstantSign.LOGCAT_NOMAL + "携带的客户信息", extra_InformationManageVo_extra);

            if (extra_InformationManageVo_extra != null) {

//                vehicleId_upLoad = extra_InformationManageVo_extra.getVehicleId();
                //2023-11-9 17:31:26
//                vehicleId_upLoad = extra_InformationManageVo_extra.getInformationId();
                //2023年11月9日17:34:03 改造车辆档案模块
                vehicleId_or_informationId_upLoad = extra_InformationManageVo_extra.getInformationId();

            }

        }

    }
}